<?php
    if(basename(__FILE__) == basename($_SERVER['PHP_SELF'])){exit();}
?>
<div id="administrativewidget" class="widgetcontainer" <?php if (!isLoggedIn() || $_SESSION['User']->UserType == "Customer") echo "style=\"display:none;\""; ?>>
    <div id="administrativeheading" class="widgetheading">
        Administration<img src="images/plus.jpg"/>
    </div>
    <div id="administrative" class="widget">
        <script type="text/javascript">
            $("#administrativeheading").data("divlink", $("#administrative"));
            $("#administrative").data("heading", $("#administrativeheading"));
            $("#administrativeheading").data("clear", function() {
                $("#sales_report_input_start").val("");
                $("#sales_report_input_end").val("");
                $("#revenue_report_type").val("");
                $("#revenue_report_input").val("");
                $("#order_list_type").val("");
                $("#order_list_input").val("");
            });
        </script>
        <div id="clear"></div>
        <div >
            <div id="administration_manager" <?php if (!isLoggedIn() || $_SESSION['User']->UserType == "Customer" || $_SESSION['User']->UserType == "Representative") echo "style=\"display:none;\""; ?>>
                
                
                <h2>Manager Level Administration</h2><br />
                <b>Update Stock Prices</b>
                <br /><br />
                <form>
                    Stock Search: <input id="stocksearch_manager" style="margin-left:10px;margin-right:30px;width:200px;" type="text" />
                    <input type="submit" class="button blue" value="Lookup" onclick="doStockLookup2($('#stocksearch_manager').val());return false;"/>
                </form>
                
                <br />
                <div id="stock_edit_result" style="display:none;"></div>
                <table id="stock_manager_table" class="rounded-corner sortable">
                    <thead style="text-align:center;"><tr>
                        <th>Stock Symbol</th><th>Stock Description</th><th>Share Price</th><th>Volume</th><th>Edit Price</th>
                    </tr></thead>
                    <tbody id="stock_manager_table_body">
                    </tbody>
                </table>
                
                
                <br /><br />
                <hr />
                <br />
                <form><table>
                    <tr><td>Enter a start date: </td><td><input id="sales_report_input_start" type="text" /></td><td style="margin-right:20px;position:inline;" id="sales_report_input_start_v"></td></tr>
                    <tr><td>Enter an end date: </td><td><input id="sales_report_input_end" type="text" /></td><td style="margin-right:20px;position:inline;" id="sales_report_input_end_v"></td></tr>
                    <tr style="height:20px;"></tr>
                    <tr><td colspan="3"><input type="submit" class="button blue" onclick="salesReport();return false;" value="Generate Sales Report"/></td></tr>
                </table></form>
                <br /><br />
                <hr />
                <br />
                <form><table>
                    <tr><td>Generate Revenue Report by: </td><td><select id="revenue_report_type"><option value="stock_symbol">Stock Symbol</option><option value="stock_type">Stock Type</option><option value="customer_id">Customer ID</option></select></td></tr>
                    <tr><td>Query: </td><td><input id="revenue_report_input" type="text" /></td></tr>
                    <tr style="height:20px;"></tr>
                    <tr><td colspan="3"><input type="submit" class="button blue" onclick="revenueReport();return false;" value="Generate Revenue Report"/></td></tr>
                </table></form>
                <br /><br />
                <hr />
                <br />
                <form><table>
                    <tr><td>Generate Order List by:</td><td><select id="order_list_type"><option value="stock_symbol">Stock Symbol</option><option value="customer_id">Customer ID</option></select></td></tr>
                    <tr><td>Stock Symbol or Customer ID:</td><td><input id="order_list_input" type="text"></input></td></tr>
                    <tr style="height:20px;"></tr>
                    <tr><td colspan="3"><input type="submit" class="button blue" onclick="orderList();return false;" value="Generate Order List" /></td></tr>
                </table></form>
                <br /><br />
                <hr />
                <br />
                <button type="button" class="button blue" onclick="comprehensiveStockList();return false;">Comprehensive Stock List</button>
                <button type="button" class="button blue" onclick="mostActiveStocks();return false;">Most Actively Traded Stocks</button>
                <br /><br /><hr/>
            </div>
            
            
            <div id="administration_representative">
                <h2>Representative Level Administration</h2><br />
                <button type="button" class="button blue" onclick="customerMailingList();return false;">Generate Customer Mailing List</button>
                <br /><br />
                <hr />
                <br />
                <form>
                    <div id="suggest_result" style="display:none;"></div>
                    Enter the ID of the customer: <input id="stock_suggest_input" type="text">
                    <br/><br/>
                    <input type="submit" class="button blue" value="Generate Stock Suggestions" onclick="getStockSuggest();return false;" />
                </form>
                <br /><br /><br />
            </div>
            
            <!--<hr />-->
            
            
        </div>
        
    </div>
    <br />
</div>
<script type="text/javascript">
    function getStockSuggest() {
        $("#suggest_result").hide();
        $.ajax({
            type: 'POST',
            url: '../backend/suggest_stock.php',
            data: {
                uid: $("#stock_suggest_input").val()
            },
            success: function(data) {
                try {
                    var data2 = eval(data);
                    $("#suggest_result").attr("class", "success");
                    $("#suggest_result").text(data2.toString());
                    $("#suggest_result").show();
                } catch (e) {
                    $("#suggest_result").attr("class", "error");
                    $("#suggest_result").html(data);
                    $("#suggest_result").show();
                }
            },                    
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                $("#suggest_result").attr("class", "error");
                $("#suggest_result").text(textStatus);
                $("#suggest_result").show();
            }
        });
    }
    function comprehensiveStockList() {
        window.open('stocklisting.php','Stock List');
    }
    function customerMailingList() {
        window.open('mailinglist.php','Customer Mailing List');
    }
    function salesReport() {
        window.open('sales_report.php?type=time_range&start=' + $("#sales_report_input_start").val() + '&end=' + $("#sales_report_input_end").val(), 'Sales Report');
    }
    function revenueReport() {
        window.open('sales_report.php?type='+$("#revenue_report_type").val()+ '&q=' + $("#revenue_report_input").val(), 'Sales Report');
    }
    
    function orderList() {
        window.open('order_list.php?type=' + $("#order_list_type").val() + '&q=' + $("#order_list_input").val(), 'Order List');
    }
    
    function mostActiveStocks() {
        window.open('active_stocks.php', 'Most Actively Traded Stocks');
    }
    
    $("#sales_report_input_start").qtip({
        api: { onRender: function() {
            $('#sales_report_input_start').bind('focus keyup change', function() {
                var d = $("#sales_report_input_start").val();
                var v = $("#sales_report_input_start_v");
                if (!validDate(d)) {
                    v.attr("class", "invalid");
                } else {
                    v.attr("class", "valid");
                }
            });
        }},
        content: "Enter the start date. (Format: 1990-05-29)", show: { when: 'focus keyup change', delay: 0 }, hide: {when: 'blur', delay: 0}, style: {name: 'dark'}, position: {corner: {tooltip: 'leftMiddle',target: 'rightMiddle'},adjust: {x: 30}}
    });
    $("#sales_report_input_end").qtip({
        api: { onRender: function() {
            $('#sales_report_input_end').bind('focus keyup change', function() {
                var d = $("#sales_report_input_end").val();
                var v = $("#sales_report_input_end_v");
                if (!validDate(d)) {
                    v.attr("class", "invalid");
                } else {
                    v.attr("class", "valid");
                }
            });
        }},
        content: "Enter the end date. (Format: 1990-05-29)", show: { when: 'focus keyup change', delay: 0 }, hide: {when: 'blur', delay: 0}, style: {name: 'dark'}, position: {corner: {tooltip: 'leftMiddle',target: 'rightMiddle'},adjust: {x: 30}}
    });
    $("#stocksearch_manager").autocomplete({
        delay: 100,
        highlight: true,
        source: 'backend/suggestion.php',
        search: function () {
            var term = extractLast(this.value);
            if (term.length < 1) return false;
        },
        focus: function () {
            return false;
        },
        select: function (event, ui) {
            var terms = split(this.value);
            terms.pop();
            terms.push(ui.item.value);
            terms.push("");
            this.value = terms.join(", ");
            return false;
        },
        source: function (request, response) {
            $.getJSON("../backend/autosuggest.php", {
                term: extractLast(request.term)
            }, response);
        }
    });
    function updateValue() {
        
    }
    function doStockLookup2(terms) {
        if (terms == "") {
            $("#stock_manager_table_body > tr").remove();
            var tr = $("<tr>");
            tr.append($("<td colspan='4'>").text("Please enter some stocks to lookup!"));
            $("#stock_manager_table_body").append(tr);
            return;
        }
        $("#stock_edit_result").hide();
        $.ajax({
            type: 'POST',
            url: '../backend/stock_lookup.php',
            dataType: 'json',
            data: {
                stocks: terms
            },
            success: function(data) {
                $("#stock_manager_table_body > tr").remove();
                var any = false;
                $.each(data, function(key, value) {
                    any = true;
                    var tr = $("<tr>");
                    tr.append($("<td>").text(key));
                    tr.append($("<td>").text(value["StockName"]));
                    tr.append($("<td style='text-align:right;'>").text(priceFormat(value["SharePrice"])));
                    tr.append($("<td style='text-align:right;'>").text(value["Shares"]));
                    
                    var form = $("<form>");
                    form.append($("<input type='text'>"));
                    var submit = $("<input type='submit' class='small blue button'>");
                    submit.bind('submit click', function(e) {
                        var stockSym = $(e.currentTarget.parentElement.parentElement.parentElement.childNodes[0]).text();
                        var newVal = e.currentTarget.parentElement.childNodes[0].value;
                        $.ajax({
                            type: 'POST',
                            url: '../backend/edit_stock.php',
                            dataType: 'json',
                            data: {
                                type: "stock_price",
                                stock: stockSym,
                                value: newVal
                            },
                            success: function(data) {
                                if (data["Success"] == null) return;
                                if (data["Success"] == 1) {
                                    $(e.currentTarget.parentElement.parentElement.parentElement.childNodes[2]).text(newVal);
                                    $("#stock_edit_result").attr('class', 'success');
                                    $("#stock_edit_result").text("Stock value successfully updated.");
                                    $("#stock_edit_result").show();
                                } else {
                                    $("#stock_edit_result").attr('class', 'error');
                                    $("#stock_edit_result").text(data['Msg']);
                                    $("#stock_edit_result").show();
                                }
                            },
                            error: function(XMLHttpRequest, textStatus, errorThrown) {
                            }
                        });
                        
                        e.preventDefault();
                        return false;
                    });
                    form.append(submit);
                    
                    tr.append($("<td>").append(form));
                    $("#stock_manager_table_body").append(tr);
                });
                if (!any) {
                    var tr = $("<tr>");
                    tr.append($("<td colspan='4'>").text("No stocks found!"));
                    $("#stock_manager_table_body").append(tr);
                }
            },                    
            error: function(XMLHttpRequest, textStatus, errorThrown) {
            }
        });
    }
</script>